package main

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
)

//var store = sessions.NewCookieStore([]byte("alongstory"))

func loginHandler(w http.ResponseWriter, r *http.Request) {
	fmt.Println("Login Handler")
	var user User

	// 处理 GET 请求，获取 URL 参数
	userType := r.URL.Query().Get("userType")
	username := r.URL.Query().Get("username")
	password := r.URL.Query().Get("password")

	// session, _ := store.Get(r, "session-spider")
	// //从cookie中获取数据
	// if userType == "" {
	// 	userType, _ = session.Values["userType"].(string)
	// }
	// if username == "" {
	// 	username, _ = session.Values["username"].(string)
	// }
	// if password == "" {
	// 	password, _ = session.Values["password"].(string)
	// }
	// //从文本框中获取数据
	// if userType != "" {
	// 	session.Values["userType"] = userType
	// }
	// if username != "" {
	// 	session.Values["username"] = username
	// }
	// if password != "" {
	// 	session.Values["password"] = password
	// }
	// //保存session信息
	// session.Save(r, w)

	// fmt.Printf("Received params: userType=%s, username=%s, password=%s\n", userType, username, password)

	// 根据不同的userType进行不同的处理
	if userType == "comuser" || userType == "admin" {
		err := db.QueryRow(context.Background(), "SELECT * FROM shopping.p_user WHERE role = $1 AND username = $2 AND password = $3", userType, username, password).Scan(&user.UserType, &user.Username, &user.Phonenumber, &user.Idnumber, &user.Email, &user.Password)
		if err != nil {
			fmt.Printf("Database query error: %v\n", err)
			http.Error(w, "Invalid username or password", http.StatusUnauthorized)
			return
		}
	} else if userType == "business" {
		err := db.QueryRow(context.Background(), "SELECT * FROM shopping.p_business WHERE role = $1 AND username = $2 AND password = $3", userType, username, password).Scan(&user.UserType, &user.Username, &user.Phonenumber, &user.Idnumber, &user.Email, &user.Password)
		if err != nil {
			fmt.Printf("Database query error: %v\n", err)
			http.Error(w, "Invalid username or password", http.StatusUnauthorized)
			return
		}
	} else {
		fmt.Printf("Invalid userType: %s\n", userType)
		http.Error(w, "Invalid userType", http.StatusBadRequest)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(user)
}
